Imports System.IO

Public Class FileResponse
    Inherits Response
    Implements IDisposable

    Private Const BUFFER_SIZE = 4096

    Private ReadOnly _Input As Stream
    Private ReadOnly _Filename As String

    Public Sub New(ByVal filename As String, ByVal input As Stream)

        MyBase.New(Net.HttpStatusCode.OK)

        _Input = input
        _Filename = filename

    End Sub

    Public ReadOnly Property Input() As Stream
        Get
            Return _Input
        End Get
    End Property

    Public ReadOnly Property Filename() As String
        Get
            Return _Filename
        End Get
    End Property

    Public Sub Save(ByVal path As String)

        Using fs As FileStream = File.Create(path)
            Dim buffer(BUFFER_SIZE - 1) As Byte
            Dim count As Integer = _Input.Read(buffer, 0, BUFFER_SIZE)
            While count <> 0
                fs.Write(buffer, 0, count)
                count = _Input.Read(buffer, 0, BUFFER_SIZE)
            End While
        End Using
    End Sub

    Public Sub Close()

        _Input.Close()

    End Sub

    Public Sub Dispose() Implements IDisposable.Dispose

        Dispose(True)
        GC.SuppressFinalize(Me)

    End Sub

    Protected Sub Dispose(ByVal flag As Boolean)

        If flag Then
            Close()
        End If
    End Sub
End Class
